package org.rayson.server.transport;

import java.io.EOFException;
import java.io.IOException;

import org.rayson.api.annotation.NotNull;
import org.rayson.api.server.ServerRequest;
import org.rayson.api.server.ServerResponse;
import org.rayson.server.Container;
import org.rayson.server.http.AsyncResponseWriter;
import org.rayson.server.http.HttpServerRequest;
import org.rayson.server.http.ServerRequestReader;
import org.rayson.server.http.ServerResponseWriter;
import org.rayson.server.rpc.ServerRequestImpl;
import org.rayson.share.transport.Connection;
import org.rayson.share.transport.NioChannel;

/**
 * 
 * TODO Add type description here.
 *
 * @author creativor
 */
public class ServerConnection implements Connection {

	private final Container container;

	private final NioChannel channel;

	private final ServerRequestReader reader;

	private final AsyncResponseWriter writer;

	private final long id;

	public ServerConnection(final Container container,
			final NioChannel channel, final long id) {
		super();
		this.container = container;
		this.channel = channel;
		this.reader = new ServerRequestReader(this);
		this.writer = new ServerResponseWriter(this);
		this.id = id;
	}

	@Override
	public void addResponse(final ServerResponse response) {
		this.writer.add(response.toHttpResponse());
	}

	@Override
	public void asyncRead() throws IOException, EOFException {
		final HttpServerRequest[] reqs = reader.read();
		if (reqs != null) {
			for (final HttpServerRequest msg : reqs) {
				container.getRequestManager().add(this.newRequest(msg));
				// // Just for testing.
				//
				// final HttpServerResponse response = new
				// HttpServerResponse();
				// response.setStartLine(new HttpStatusLine(
				// HttpConstants.HTTP_VERSION, 200, "OK"));
				// response.addHeader(new HttpHeader("Content-Type",
				// "text/html; charset=utf-8"));
				// response.setBody("Hello world!".getBytes());
				// this.writer.add(response);
			}
		}

	}

	@Override
	public void asyncWrite() throws IOException {
		writer.write();
	}

	@Override
	public void close() throws IOException {
		channel.close();

	}

	@Override
	public NioChannel getChannel() {
		return channel;
	}

	@Override
	public long getId() {
		return id;
	}

	/**
	 * @param msg
	 * @return
	 */
	ServerRequest newRequest(@NotNull final HttpServerRequest msg) {
		return new ServerRequestImpl(msg, this);
	}
}